package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.Access;

@Repository(value = "accessDao")
@Transactional(readOnly = false)
public class AccessDaoImpl implements AccessDao {

	private EntityManager em = null;
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	} 
	
	@SuppressWarnings("unchecked")
	public List<Access> getAccessList() {
		return em.createNamedQuery("Access.findAll").getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Access> getAccessListByPharmacyId(Integer pharmacyId) {
		Query  q =em.createNamedQuery("Access.findByPharmacyId");
		q.setParameter("pharmacyId",pharmacyId);
    	return q.getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Access> getAccessList(Integer userId) {
		Query  q =em.createNamedQuery("Access.findByUserId");
		q.setParameter("userId",userId);
    	return q.getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Access> getAccessList(Integer userId,Integer pharmacyId) {
		Query  q =em.createNamedQuery("Access.findByUserIdByPharmacyId");
		q.setParameter("userId",userId);		
		q.setParameter("pharmacyId",pharmacyId);		
    	return q.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Access> getAccessList(Integer userId,Integer pharmacyId, short menuId,	short submenuId) {
		Query  q =em.createNamedQuery("Access.findByUserIdByPharmacyIdByMenuIdBySubmenuId");
		q.setParameter("userId",userId);		
    	q.setParameter("pharmacyId",pharmacyId);		
		q.setParameter("menuId",menuId);		
		q.setParameter("submenuId",submenuId);		
    	return q.getResultList();
	}
	
	public Access findByPharmacyIdByUserIdByMenuIdBySubmenuIdByOptionId(Integer pharmacyId,Integer userId,short menuId, short submenuId, short optionId) {
		Access res=null;
    	Query  q = em.createNamedQuery("Access.findByPharmacyIdByUserIdByMenuIdBySubmenuIdByOptionId");
    	q.setParameter("pharmacyId",pharmacyId);		
    	q.setParameter("userId",userId);		
		q.setParameter("menuId",menuId);		
		q.setParameter("submenuId",submenuId);
		q.setParameter("optionId",optionId);
    	if(q.getResultList().size()==1)
    		res=(Access)q.getSingleResult();
    	return res;
	}
	public void add(Access access) {
		em.persist(access);
	}
	public void remove(Access access){
		em.remove(findByPharmacyIdByUserIdByMenuIdBySubmenuIdByOptionId(access.getAccessPK().getPharmacyId(),access.getAccessPK().getUserId(),access.getAccessPK().getMenuId(),access.getAccessPK().getSubmenuId(),access.getAccessPK().getOptionId()));
	}	
}
